/*
 * @author:陈旭光，Chen XuG ,chenxvguang1991@163.com
 */

var can1=document.getElementById('can1');
var ctx1=can1.getContext('2d');
var can2=document.getElementById('can2'); 
var ctx2=can2.getContext('2d');
var startBtn=document.getElementById('startGame');
var reStartBtn=document.getElementById('reStartGame');
var continueBtn=document.getElementById('continue');
var maxScore=document.getElementById('maxScore');
var music=document.getElementById('music');
var openMusic=document.getElementById('openMusic');
var closeMusic=document.getElementById('closeMusic');
var cW=can1.width;
var cH=can1.height;
var mx=400,my=300;
var gamePlay=null,//游戏状态
     pause=false,//暂停状态
     started=false,//初始状态
     musicTurn=true;//音效开闭状态
var lastTime,deltaTime;//获取每次循环时间间隔
var backGround,//背景
      ane,//海葵
      fruits,// 海葵果实
      mom,//鱼妈妈
      baby,//鱼宝宝
      collsion,//碰撞检测
      data,//数据
      dust,//浮游海藻
      circle,//圆圈特效
      sound;//音效

window.onload=game;

function  game(){
     gamePlay=true;
     backGround=new backGrondObj();
	 ane=new Ane();
	 fruits=new Fruit();
	 mom=new Mom();
	 baby=new Baby();
	 collsion=new Collsion;
	 data=new Data();
	 dust=new Dust();
	 circle=new Circle();
	 sound=new Sound();
     init();
     lastTime=Date.now();
     loop();
         };
 
function init(){
       can2.addEventListener('mousemove',mouMove,false);
       can2.addEventListener('mousedown',mouDown,false);
       ane.init();
       fruits.init();
       mom.init();
       baby.init();
       data.init();
       dust.init();
       circle.init();

}

function loop(){
      if(!pause){window.requestAnimFrame(loop);}
      deltaTime=Date.now()-lastTime;
      if(deltaTime>50)deltaTime=50;
       lastTime=Date.now();
       backGround.draw();
       ane.draw();
       fruits.draw();
       dust.draw();

       if(started){ctx2.clearRect(0,0,800,600);
              mom.draw();
              baby.draw();
              baby.drawBabyBody();
              collsion.draw();
              data.draw();
              circle.draw();}

      if(!musicTurn){sound.background.pause()}
}

//点击事件及方法

reStartGame.onclick=function(){
    this.parentNode.style.display='none';
    ctx1.clearRect(0,0,cW,cH);
    ctx2.clearRect(0,0,cW,cH);
    game();
    lastTime=Date.now();
    loop();
};

startBtn.onclick=function(){
             
              this.parentNode.style.display='none';
              started=true;
              if(musicTurn){sound.background.play();}
}
continueBtn.onclick=function(){
              this.parentNode.style.display='none';
              pause=false;
              loop();
}

music.onclick=function(){

     if(musicTurn){
             openMusic.className='showMusic';
             closeMusic.className='hidMusic';
             sound.background.pause()
             musicTurn=false;
     }
     else if(!musicTurn&&started){
              closeMusic.className='showMusic';
              openMusic.className='hidMusic';
              sound.background.play();
              musicTurn=true;
     }
}

function mouMove(e){
      if(e.offSetX||e.layerX){
      	my=e.offSetY==undefined?e.layerY:e.offSetY;
      	mx=e.offSetX==undefined?e.layerX:e.offSetX;
      }
  }

  function mouDown(e){
     
      e=e||window.event;
      if(e.button==0&&gamePlay){ pause=true;
      continueBtn.parentNode.style.display='block';
                        }
  }

  function gameOver(){
  	gamePlay=false;
    reStartGame.parentNode.style.display='block';        
  } 

//常用方法

window.requestAnimFrame = (function() {
  return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
    function( callback,element) {
      return window.setTimeout(callback, 1000 / 60);
    };
})();

  function atan(x0,y0,x1,y1){
	var deltaX=x0-x1;
	var deltaY=y0-y1;
	return Math.atan2(deltaY,deltaX)+Math.PI;
}

function lerpAngle(a, b, t) {
	var d = b - a;
	if (d > Math.PI) d = d - 2 * Math.PI;
	if (d < -Math.PI) d = d + 2 * Math.PI;
	return a + d * t;
}

function lerpDistance(aim, cur, ratio) {
	var delta = cur - aim;
	return aim + delta * ratio;
}

function calLength2(x1, y1, x2, y2) {
	return Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2);
}
//---------------background------------------
function backGrondObj(){
        this.bagImg=new Image();
        this.bagImg.src='./img/background.jpg';
}

backGrondObj.prototype={
  draw:function(){
       ctx1.drawImage(this.bagImg,0,0,800,600)
  },
}
//----------------mom-------------------------
function Mom(){
            this.body=new Image();
            this.body.src='./img/bigSwim0.png';
            this.eye=new  Image();
            this.eyeCount=0;
            this.eyeTime=0;
            this.openEye=1000;
            this.eye.src='./img/bigEye0.png';
            this.eyeImg=['./img/bigEye0.png','./img/bigEye1.png'];
            this.tail=new Image();
            this.tailImg=[];
            for(var i=0;i<8;i++){
               this.tailImg[i]='./img/bigTail'+i+'.png';
            };
            this.tailCount=1;
            this.angle=0;
            this.x=0;
            this.y=0;
}

Mom.prototype={
  init:function(){
                     this.x=400;
                     this.y=300;
  },
  draw:function(){
           this.x=lerpDistance(mx,this.x,0.95);
           this.y=lerpDistance(my,this.y,0.95);
           var angle0=atan(mx,my,this.x,this.y)
           this.angle=lerpAngle(angle0,this.angle,0.7)

           this.tail.src=this.tailImg[ (this.tailCount++)%8];

           this.eyeTime+=deltaTime;
                      if(this.eyeCount==0&&this.eyeTime>=this.openEye){
                               this.eye.src=this.eyeImg[1];
                               this.eyeTime=0;
                               this.eyeCount=1;
                               this.openEye=Math.random()*1000+500;
                      }
                      else if(this.eyeCount==1&&this.eyeTime>=200){
                               this.eye.src=this.eyeImg[0];
                               this.eyeTime=0;
                               this.eyeCount=0;
                     }

           ctx2.save();
           ctx2.translate(this.x,this.y);
           ctx2.rotate(this.angle);
                       ctx2.drawImage(this.body,-this.body.width/2,-this.body.height/2,this.body.width,this.body.height);
                       ctx2.drawImage(this.eye,-this.eye.width/2,-this.eye.height/2,this.eye.width,this.eye.height);
                       ctx2.drawImage(this.tail,11,-this.tail.height/2,this.tail.width,this.tail.height);
                       ctx2.restore();
  }
}
//----------------baby--------------------------
function Baby(){
            this.body=new Image();
            this.bodyCount=0;
            this.bodyImg=[];
            this.bodyTime=0;
            for(var i=0;i<20;i++){
                this.bodyImg[i]='./img/babyFade'+i+'.png';
            };
            this.eye=new  Image();
            this.eyeCount=0;
            this.eyeTime=0;
            this.openEye=1000;
            this.eye.src='./img/babyEye0.png';
            this.eyeImg=['./img/babyEye0.png','./img/babyEye1.png'];
            this.tail=new Image();
            this.tailImg=[];
            for(var i=0;i<8;i++){
               this.tailImg[i]='./img/babyTail'+i+'.png';
            };
            this.tailCount=1;
            this.angle=0;
            this.x=0;
            this.y=0;
}

Baby.prototype={
  init:function(){
                     this.x=400;
                     this.y=300;
  },
  draw:function(){
          if(gamePlay){
                     this.x=lerpDistance(mom.x,this.x,0.97);
                     this.y=lerpDistance(mom.y,this.y,0.97);
                     var angle0=atan(mom.x,mom.y,this.x,this.y);
                     this.angle=lerpAngle(angle0,this.angle,0.8);

                     this.tail.src=this.tailImg[ (this.tailCount++)%8];

                     this.eyeTime+=deltaTime;
                     if(this.eyeCount==0&&this.eyeTime>=this.openEye){
                               this.eye.src=this.eyeImg[1];
                               this.eyeTime=0;
                               this.eyeCount=1;
                               this.openEye=Math.random()*1000+500;
                      }
                     else if(this.eyeCount==1&&this.eyeTime>=200){
                               this.eye.src=this.eyeImg[0];
                               this.eyeTime=0;
                               this.eyeCount=0;
                     }
              }
               else{
                         this.y-=1;
                         this.tail.src=this.tailImg[ 7];
                         this.eye.src=this.eyeImg[1];
               }


            ctx2.save();
            ctx2.translate(this.x,this.y);
            ctx2.rotate(this.angle);
                 ctx2.drawImage(this.body,-this.body.width/2,-this.body.height/2,this.body.width,this.body.height);
                 ctx2.drawImage(this.eye,-this.eye.width/2,-this.eye.height/2,this.eye.width,this.eye.height);
                 ctx2.drawImage(this.tail,11,-this.tail.height/2,this.tail.width,this.tail.height);
                 ctx2.restore();
  },

       drawBabyBody:function(){
               this.body.src=this.bodyImg[this.bodyCount];
               this.bodyTime+=deltaTime;
               if(this.bodyTime>=100){
                         this.bodyCount++;
                         this.bodyTime=0
                         if(this.bodyCount>=19){
                          this.bodyCount=19;
                          gameOver();
                        };
                        
               }
       }
}
//---------------ane-----------------------------
function Ane(){
      this.x=[];
      this.y=[];
      this.num=50;
      this.alpha=0;
      this.deltaX=0
}

Ane.prototype={
       init:function(){
              for(var i=0;i<this.num;i++){
                this.x[i]=i*17+Math.random()*20;
                this.y[i]=cH-Math.random()*50-200;
              }
       },

       draw:function(){
        this.alpha+=deltaTime*0.001;
        this.deltaX=Math.floor(Math.sin(this.alpha)*50);
        
        ctx1.save();
        ctx1.lineWidth='20';
        ctx1.lineCap='round';
        ctx1.strokeStyle="rgba(59,21,78,0.5)";
             for(var i=0;i<this.num;i++){
                ctx1.beginPath();
                ctx1.moveTo(this.x[i],cH);
                ctx1.quadraticCurveTo(this.x[i],cH-150,this.x[i]+this.deltaX,this.y[i]) 
                ctx1.stroke();
             }
             ctx1.restore()
       }
}
//----------------fruit----------------------------
function Fruit(){
             this.x=[];
             this.y=[];
             this.alive=[];
             this.img=[];
             this.No=[];
             this.num=15;
             this.r=[];
             this.spead=[];
             this.cr=[];
             this.x0=[];
}

Fruit.prototype={
  init:function(){
                     for(var i=0;i<this.num;i++){
                          this.alive[i]=false;
                          this.x[i]=0;
                          this.x0[i]=0;
                          this.y[i]=0;
                          this.img[i]=new Image();
                          var color=Math.random();
                          if(color<0.8){ 
                      this.img[i].src="./img/fruit.png";
                      this.cr[i]=0;
                            }
                         else{
                      this.img[i].src="./img/blue.png";
                      this.cr[i]=1;
                         }
        }          
  },

  born:function(i){
        this.alive[i]=true;
                    this.No[i]=Math.floor(Math.random()*50);
                    this.x[i]=ane.x[ this.No[i]]+ane.deltaX;
                    this.y[i]=ane.y[ this.No[i]];
                    this.r[i]=3;
                    this.spead[i]=Math.random()*0.7+0.2;
  },

  draw:function(){
             var aliveNum=0;
                        for(var i=0;i<this.num;i++){
                          if(this.alive[i]) aliveNum++;
                        }
                       
                        if(aliveNum<this.num){
                          for(var i=0;i<this.num;i++){
                            if(!this.alive[i]) {this.born(i)};

                         }
                        }


                        for(var i=0;i<this.num;i++){
                          if(this.alive[i]){
                               if(this.r[i]<15){
                                 ctx1.drawImage(this.img[i],this.x[i]-this.r[i]/2+ane.deltaX,this.y[i]-this.r[i]/2,this.r[i],this.r[i]);
                                 this.r[i]+=0.01*deltaTime;
                                 this.x0[i]=this.x[i]+ane.deltaX;
                               }
                               else{
                                 this.r[i]=15;
                                 if(this.cr[i]==0){this.y[i]-=this.spead[i];}
                                 else{this.y[i]-=this.spead[i]*0.6;};
                                 ctx1.drawImage(this.img[i],this.x0[i]-this.r[i]/2,this.y[i]-this.r[i]/2,this.r[i],this.r[i]);
                                 if(this.y[i]<10){
                                  this.alive[i]=false;
                                 }

                               }
                             }
                        }
                        
            },

}
//----------------dust----------------------------
var Dust=function(){
         this.x=[];
         this.y=[];
         this.img=[];
         this.num=30;
         this.alpha=0;
         this.deltaX=0;
}
Dust.prototype={
      init:function(){
                for(var i=0;i<this.num;i++){
                  this.y[i]=Math.random()*400+50;
                  this.x[i]=Math.random()*800;
                  this.img[i]=new Image();
                  this.img[i].src='./img/dust'+Math.floor(Math.random()*7)+'.png';
                }
      },
      draw:function(){
        this.alpha+=deltaTime*0.001;
        this.deltaX=Math.floor(Math.sin(this.alpha)*50);
         ctx1.save()
                  for(var i=0;i<this.num;i++){
                        ctx1.drawImage(this.img[i],this.x[i]+this.deltaX,this.y[i],this.img[i].width,this.img[i].height);
                  }
                ctx1.restore();
      }

}
//----------------circle--------------------------
var Circle=function(){
          this.num=30;
          this.x=[];
          this.y=[];
          this.r=[];
          this.alive=[];
          this.alpha=[];
          this.type=[];
}

Circle.prototype={
  init:function(){
                      for(var i=0;i<this.num;i++){
                  this.y[i]=0;
                  this.x[i]=0;
                  this.r[i]=30;
    this.alpha[i]=0.5;
                  this.alive[i]=false;
                   this.type[i]=false;
                }
  },
  draw:function(){
                         
                        for(var i=0;i<this.num;i++){
                          if( this.alive[i]){

                            this.r[i]+=deltaTime*0.05;
                            if(this.r[i]>60){
                              this.alive[i]=false;
                              
                            }
                            this.alpha[i]-=0.01;
      ctx1.save();
      ctx1.beginPath();
      ctx1.lineWidth=2;
      ctx1.shadowBlur=3;
      ctx1.shadowColor="white";
      ctx1.strokeStyle=this.type[i]?('rgba(255,64,64,'+this.alpha[i]+')'):('rgba(255,255,255,'+this.alpha[i]+')');
      ctx1.arc(this.x[i],this.y[i],this.r[i],0,2*Math.PI);
      ctx1.stroke();
      ctx1.restore();
                                    
                          }
                        }
  },
  born:function(x,y,l){

    for(var i=0;i<this.num;i++){
      this.type[i]=l;
      this.r[i]=30;
      this.alive[i]=true;
      this.alpha[i]=0.5;
      this.x[i]=x;
      this.y[i]=y;
      return;
        }
              }

}
//----------------collision-----------------------
function Collsion(){

}

Collsion.prototype={
    draw:function(){
      for(var i=0;i<fruits.num;i++){
        if(calLength2(mom.x,mom.y,fruits.x[i],fruits.y[i])<=1600&&fruits.r[i]==15){
                                         if(fruits.cr[i]==0){
                                              data.orange++;
                                         }
                                         else if((fruits.cr[i]==1)){
                                               data.blue++;
                                         }
                                              
                              fruits.alive[i]=false;
                                          circle.born(mom.x,mom.y,false);

                 }
      }

      if(calLength2(mom.x,mom.y,baby.x,baby.y)<=1600&&(data.orange!=0||data.blue!=0)&&gamePlay){
                           circle.born(mom.x,mom.y,true);
        baby.bodyCount=0;
        data.scroe+=data.orange*10+data.blue*15;
        if(data.scroe>maxScore.innerHTML) maxScore.innerHTML=data.scroe;
        data.orange=0;
        data.blue=0;
                            if(musicTurn){sound.momMeetBaby.play();}
      }
    }
}
//----------------data----------------------------
function Data(){
             this.orange=0;
             this.blue=0;
             this.scroe=0;
             this.orangeImg=new Image();
             this.orangeImg.src="./img/fruit.png";
             this.blueImg=new Image();
             this.blueImg.src="./img/blue.png";
}

Data.prototype={
  init:function(){

  },
  draw:function(){
        ctx2.save();
        ctx2.font="40px  Arial";
        ctx2.fillStyle='white';
        ctx2.textAlign="center";
        ctx2.fillText('score:'+this.scroe,400,550);
        ctx2.restore();

        ctx2.save();
        ctx2.font="20px  Arial";
        ctx2.fillStyle='white';
        ctx2.textAlign="center";
        ctx2.drawImage( this.orangeImg,320,483,20,20);
        ctx2.fillText(':'+this.orange,350,500);
        ctx2.drawImage( this.blueImg,420,483,20,20);
        ctx2.fillText(':'+this.blue,450,500);

        ctx2.restore();
  }
}
//----------------sound--------------------------
function Sound(){
       this.momMeetBaby=new Audio('./sound/mmb.mp3');
       this.background=new Audio('./sound/background.mp3');
       this.background.loop='loop';
}